import pandas as pd


class JobData:
    DATA_PATH = r"D:\PycharmProjects\51jobProject\teacher\data\teacher_job_data.csv"

    def __init__(self):
        self.origin_df = None

    def load_data(self):
        self.origin_df = pd.read_csv(self.DATA_PATH)

    def get_data(self):
        return self.origin_df

    def get_origin_info(self):
        return self.origin_df.info()

    def get_abnormal_examples(self):
        ab_examples = self.origin_df[(self.origin_df['province'] == '浙江')].head(2).reset_index()
        ab_examples.drop(['index'], axis=1, inplace=True)
        ab_examples = ab_examples[['jobName', 'companyName', 'province', 'city']]
        return ab_examples

    def get_head(self):
        return self.origin_df.head(5)

    def fill_amount_average(self):
        amount_df = self.origin_df[(self.origin_df['amount'] != '若干')]
        amount_df['amount'] = amount_df['amount'].astype(int)
        amount_average = int(sum(amount_df['amount']) / len(amount_df))
        print(amount_average)
        amount_list = list()
        for index, row in self.origin_df.iterrows():
            if row['amount'] == '若干':
                amount_list.append(amount_average)
            else:
                amount_list.append(row['amount'])
        # origin_df['amount'].replace('若干', str(amount_average))
        self.origin_df['amount'] = amount_list
        self.origin_df['amount'] = self.origin_df['amount'].astype(int)
        return self.origin_df.iloc[20: 22]

    def change_to_category(self):
        int_cols = {'amount', 'maxWage', 'minWage'}
        columns = set(self.origin_df.columns)
        object_cols = columns.difference(int_cols)
        for object_col in object_cols:
            self.origin_df[object_col] = self.origin_df[object_col].astype("category")

    def get_province_statistic(self):
        return self.origin_df['province'].value_counts()

    def get_teacher_category(self):
        return self.origin_df[self.origin_df['jobCategory'].str.contains('教师')]

    def get_type_category(self):
        return self.origin_df['companyTypeName'].value_counts()

    def get_popular_major_all(self):
        job_record_col = {'jobRecord', 'jobName'}
        drop_cols = set(self.origin_df.columns).difference(job_record_col)
        job_record_df = self.origin_df[(self.origin_df['jobRecord'] != '专业未分类') & (self.origin_df['jobRecord'] != '专业不限')]
        job_record_df = job_record_df.groupby('jobRecord').agg('count')
        job_record_df = job_record_df.sort_values('jobName', ascending=False)
        job_record_df = job_record_df.drop(list(drop_cols), axis=1)
        job_record_df = job_record_df.reset_index()
        job_record_df = job_record_df.rename(columns={'jobName': '岗位数量', 'jobRecord': '热门专业'})
        top_job_record_df = job_record_df.head(10)
        return top_job_record_df

    def get_popular_major_teacher(self):
        job_record_col = {'jobRecord', 'jobName'}
        drop_cols = set(self.origin_df.columns).difference(job_record_col)
        teacher_record_df = self.origin_df[(self.origin_df['jobRecord'] != '专业未分类') &
                                           (self.origin_df['jobRecord'] != '专业不限') &
                                           (self.origin_df['jobCategory'].str.contains('教师'))]
        teacher_record_df = teacher_record_df.groupby(['jobRecord']).agg('count')
        teacher_record_df = teacher_record_df.sort_values('jobName', ascending=False)
        teacher_record_df = teacher_record_df.drop(list(drop_cols), axis=1)
        teacher_record_df = teacher_record_df.reset_index()
        teacher_record_df = teacher_record_df.rename(columns={'jobName': '教师岗位数', 'jobRecord': '热门专业'})
        top_teacher_record_df = teacher_record_df.head(10)
        return top_teacher_record_df

    def get_popular_major_merge(self):
        record_result = pd.merge(self.get_popular_major_teacher(), self.get_popular_major_all(), on=['热门专业'],
                                 how='inner')
        record_result['差值'] = record_result['岗位数量'] - record_result['教师岗位数']
        return record_result

    def get_max_min_difference_teacher(self):
        record_result = self.get_popular_major_merge()
        max_difference_index = record_result['差值'].argmax()
        min_difference_index = record_result['差值'].argmin()
        max_difference_line = record_result.iloc[max_difference_index: max_difference_index + 1]
        min_difference_line = record_result.iloc[min_difference_index: min_difference_index + 1]
        combine_df = max_difference_line.append(min_difference_line)
        return combine_df

    def get_group_company(self):
        columns = set(self.origin_df.columns)
        groupy = {'province', 'companyTypeName', 'jobName'}
        differ = columns.difference(groupy)
        df = self.origin_df.groupby(['province', 'companyTypeName']).count()
        df.drop(list(differ), axis=1, inplace=True)
        df = df.rename(columns={'jobName': 'count'})
        df = df.groupby(['province'], sort=False).apply(lambda x: x.sort_values('count', ascending=False))
        df = df.rename(columns={'count': '岗位总数'})
        return df

    def get_one_and_two(self):
        one_and_two_df = self.origin_df[((self.origin_df['province'] == '上海') |
                                         (self.origin_df['province'] == '北京') |
                                         (self.origin_df['province'] == '广东') |
                                         (self.origin_df['province'] == '河北') |
                                         (self.origin_df['province'] == '陕西')) &
                                        ((self.origin_df['companyTypeName'] == '双一流院校') |
                                         (self.origin_df['companyTypeName'] == '普通本科院校'))]
        one_and_two_df = one_and_two_df.drop(['maxWage', 'minWage'], axis=1)
        one_and_two_df = one_and_two_df.pivot_table(index=['province'], columns=['companyTypeName'],
                                                    values='companyNatureName', aggfunc='count')
        one_and_two_df['普通本科院校'] = one_and_two_df['普通本科院校'].fillna(0)
        one_and_two_df['差值'] = one_and_two_df['双一流院校'] - one_and_two_df['普通本科院校']
        return one_and_two_df

    def get_data_in_shanghai(self):
        return self.origin_df[(self.origin_df['province'] == '上海')]

    def get_divided_in_shanghai(self):
        shanghai_df = self.get_data_in_shanghai()
        shanghai_select_df = shanghai_df[
            (shanghai_df['companyTypeName'] == '普通本科院校') | (shanghai_df['companyTypeName'] == '双一流院校')]
        shanghai_result = shanghai_select_df[(shanghai_select_df['jobCategory'].str.contains('教师')) | (
            shanghai_select_df['jobCategory'].str.contains('科研'))]
        categories = list()
        for index, row in shanghai_result.iterrows():
            if '教师' in row['jobCategory']:
                categories.append('教师岗')
            else:
                categories.append('科研岗')
        shanghai_result['category'] = categories
        shanghai_result = shanghai_result.drop(['maxWage', 'minWage'], axis=1)
        shanghai_result = shanghai_result.pivot_table(index=['companyTypeName'], columns=['category'],
                                                      values='companyNatureName', aggfunc='count')
        return shanghai_result

    def get_last_five_month(self):
        shanghai_df = self.get_data_in_shanghai()
        this_year = shanghai_df[~(shanghai_df['releaseTime'].str.contains('2022'))]
        month_dict = {'01': 0, '02': 0, '03': 0, '04': 0, '05': 0}
        for index, row in this_year.iterrows():
            month = row['releaseTime'].split('-')[0]
            month_dict[month] += 1
        return month_dict

